package com.xuecheng.learning.service;

import com.alibaba.fastjson.JSON;
import com.xuecheng.framework.domain.course.TeachplanMedia;
import com.xuecheng.framework.domain.learning.XcLearningCourse;
import com.xuecheng.framework.domain.learning.response.GetMediaResult;
import com.xuecheng.framework.domain.learning.response.LearningCode;
import com.xuecheng.framework.domain.task.XcTask;
import com.xuecheng.framework.domain.task.XcTaskHis;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.learning.dao.XcLearningCourseRepository;
import com.xuecheng.learning.dao.XcTaskHisRepository;
import com.xuecheng.learning.learning.CourseSearchClient;
import com.xuecheng.learning.mq.ChooseCourseTask;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName CourseLearning
 * @Description (这里用一句话描述这个类的作用)
 * @date 2020/3/7 13:25
 * @since V1.0
 */
@Service
public class CourseLearningService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CourseLearningService.class);


    @Autowired
    private CourseSearchClient courseSearchClient;

    @Autowired
    private XcLearningCourseRepository xcLearningCourseRepository;

    @Autowired
    private XcTaskHisRepository xcTaskHisRepository;

    /**
     * @Description 添加选课
     * @author ShengJinFeng
     * @date 2020/3/14
     */
    @Transactional
    public ResponseResult addCourse(XcTask xcTask) {
        if(xcTask == null || StringUtils.isEmpty(xcTask.getId()) || StringUtils.isEmpty(xcTask.getRequestBody())){
            ExceptionCast.cast(LearningCode.CHOOSECOURSE_TASKISNULL);
        }
        try {
            String requestBody = xcTask.getRequestBody();
            Map map = JSON.parseObject(requestBody, Map.class);
            String userId = (String) map.get("userId");
            String courseId = (String) map.get("courseId");
            String valid = (String) map.get("valid");
            Date startTime = null;
            Date endTime = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
            if(map.get("startTime")!=null){
                startTime =dateFormat.parse((String) map.get("startTime"));
            }
            if(map.get("endTime")!=null){
                endTime =dateFormat.parse((String) map.get("endTime"));
            }
            if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(courseId)){
                ExceptionCast.cast(LearningCode.ADD_CHOOSECOURSE_FULL);
            }
            XcLearningCourse xcLearningCourse = xcLearningCourseRepository.findByUserIdAndCourseId(userId, courseId);
            if (xcLearningCourse != null){
                xcLearningCourse.setValid(valid);
                xcLearningCourse.setStartTime(startTime);
                xcLearningCourse.setEndTime(endTime);
                xcLearningCourse.setStatus("501001");
                xcLearningCourseRepository.save(xcLearningCourse);
            }else{
                xcLearningCourse = new XcLearningCourse();
                xcLearningCourse.setUserId(userId);
                xcLearningCourse.setCourseId(courseId);
                xcLearningCourse.setValid(valid);
                xcLearningCourse.setStartTime(startTime);
                xcLearningCourse.setEndTime(endTime);
                xcLearningCourse.setStatus("501001");
                xcLearningCourseRepository.save(xcLearningCourse);
            }
            //向历史任务表播入记录
            Optional<XcTaskHis> optional = xcTaskHisRepository.findById(xcTask.getId());
            if (!optional.isPresent()){
                XcTaskHis xcTaskHis = new XcTaskHis();
                BeanUtils.copyProperties(xcTask,xcTaskHis);
                xcTaskHisRepository.save(xcTaskHis);
            }
            return new ResponseResult(CommonCode.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.error("添加选课失败，失败原因：{}",e.getMessage());
            ExceptionCast.cast(LearningCode.CHOOSECOURSE_TASKISNULL);
            return new ResponseResult(CommonCode.FAIL);
        }
    }

    /**
     * @Description 获取课程学习地址
     * @author ShengJinFeng
     * @date 2020/3/7
     */
    public GetMediaResult getmedia(String courseId, String teachplanId) {
        //验证当前用户是否有观看权限

        //根据计划id获取媒资文件地址
        TeachplanMedia teachplanMedia = courseSearchClient.getmediaByTeachplanId(teachplanId);
        if (teachplanMedia == null || StringUtils.isEmpty(teachplanMedia.getMediaUrl())){
            ExceptionCast.cast(LearningCode.LEARNING_GETMEDIA_ERROR);
        }
        return new GetMediaResult(CommonCode.SUCCESS,teachplanMedia.getMediaUrl());
    }
}
